package dilmaj.server;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import dilmaj.client.CommentJDO;
import dilmaj.client.CommentService;
import dilmaj.client.TermJDO;
import dilmaj.client.UserJDO;
import dilmaj.client.UserService;
import dilmaj.shared.CommentVO;
import dilmaj.shared.TermVO;
import dilmaj.shared.UserVO;

public class CommentServiceImpl extends RemoteServiceServlet implements
		CommentService {
	public List<CommentVO> getAllComments(List<Long> commentIDs) {
		ArrayList<CommentVO> commentVOs=new ArrayList<CommentVO>();
		
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    String query = "select from " + CommentJDO.class.getName();
	    List<CommentJDO> commentJDOs = (List<CommentJDO>) pm.newQuery(query).execute();
	    
	    Iterator iterator=commentJDOs.iterator();
	    while (iterator.hasNext()) {
	    	CommentJDO currentComment=(CommentJDO)iterator.next();
	    	CommentVO commentVO=new CommentVO(currentComment);
	    	
	    	Iterator iterator2=commentIDs.iterator();
	    	while (iterator2.hasNext()) {
	    		Long currentID=(Long)iterator2.next();
	    		
	    		if (currentID.longValue()==commentVO.getId().longValue())
	    			commentVOs.add(commentVO);
	    	}
	    }
	    
	    pm.close();
	    return commentVOs;
	}

	public CommentVO addComment(CommentVO newComment) {
        Long userId=(Long)getThreadLocalRequest().getSession().getAttribute("userid");
        String userName=(String)getThreadLocalRequest().getSession().getAttribute("username");
        if (userId!=null)
        	newComment.setUserID(userId);
        if (userName!=null)
        	newComment.setUserName(userName);
        CommentJDO commentJDO = new CommentJDO(newComment);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(commentJDO);
        } finally {
            pm.close();
        }
        
        newComment.setId(commentJDO.getId());
        
        return newComment;
	}

}
